package com.yun.user.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.ApUserDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.vos.ApUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import com.yun.user.service.ApUserService;
import com.yun.user.mapper.ApUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author Excell
 * @description 针对表【ap_user(APP用户信息表)】的数据库操作Service实现
 * @createDate 2025-07-13 15:21:33
 */
@Service
@RequiredArgsConstructor
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser>
        implements ApUserService {

    private final ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(ApUserDTO userDTO) {
        HashMap<String, Object> map = new HashMap<>();

        // 判断账号密码是否为空,当账号密码任意一个为空则使用游客账号
        if (StringUtils.isEmpty(userDTO.getPassword()) || StringUtils.isEmpty(userDTO.getPhone())) {
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }

        // 获取用户名和密码
        // 根据手机号获取用户
        // 构造查询条件
        LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<ApUser>()
                .eq(ApUser::getPhone, userDTO.getPhone());

        ApUser apUser = apUserMapper.selectOne(queryWrapper);

        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 获取密码
        String password = MD5Utils.encode(userDTO.getPassword() + apUser.getSalt());
        // 校验密码
        if (!password.equals(apUser.getPassword())) {
            // 密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        // 返回数据
        // 生成token
        ApUserVO apUserVO = new ApUserVO();
        BeanUtils.copyProperties(apUser, apUserVO);
        map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
        map.put("user", apUserVO);

        return ResponseResult.okResult(map);
    }
}




